package controller;

import pojo.User;
import service.UserService;
import view.Register;
import view.SignIn;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SignInListener implements ActionListener {
    private Register register;
    private UserService userService;
    private JTextField tfNum;
    private JPasswordField tfPwd;
    private SignIn dialog;

    public SignInListener(SignIn dialog) {
        super();
        this.dialog = dialog;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("1")) {
            userService = new UserService();
            tfNum = dialog.getTfNum();
            tfPwd = dialog.getTfPwd();
            if (tfNum.getText().trim().equals("") && tfPwd.getText().trim().equals("")) {
                JOptionPane.showMessageDialog(dialog, "请你输入账户后再登录", "提示", JOptionPane.WARNING_MESSAGE);
            } else if (tfPwd.getText().trim().equals("")) {
                JOptionPane.showMessageDialog(dialog, "请你输入密码后再登录", "提示", JOptionPane.WARNING_MESSAGE);
            } else {
                User user = userService.search(tfNum.getText()) == null ? null : userService.search(tfNum.getText());
                if (user == null) {
                    JOptionPane.showMessageDialog(dialog, "请先注册账户", "提示", JOptionPane.WARNING_MESSAGE);
                    new Register();
                } else {
                    boolean check = userService.check(tfNum.getText(), tfPwd.getText());
                    if (check == false) {
                        JOptionPane.showMessageDialog(dialog, "密码错误", "提示", JOptionPane.WARNING_MESSAGE);
                    } else if (check == true) {
                        dialog.getFrame().setUserId(dialog.getTfNum().getText());
                        dialog.getFrame().setUser(user);
                        dialog.setVisible(false);
                        dialog.getFrame().setVisible(true);
                        dialog.dispose();
                    }

                }
            }
        }
            if (e.getActionCommand().equals("2")) {
                new Register();
            }
            if (e.getActionCommand().equals("3")) {
                System.exit(0);
            }

    }
}